package com.sec.etech.org.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ArrayUtil;
import com.github.pagehelper.Page;
import com.sec.etech.org.dao.OrgRelationMapper;
import com.sec.etech.org.model.EtechUser;
import com.sec.etech.org.service.EtechGroupService;
import com.sec.etech.org.service.EtechRelationService;
import org.openbpm.base.api.aop.annotion.CatchErr;
import org.openbpm.base.api.exception.BusinessError;
import org.openbpm.base.api.query.QueryFilter;
import org.openbpm.base.api.query.QueryOP;
import org.openbpm.base.api.response.impl.ResultMsg;
import org.openbpm.base.db.model.page.PageResult;
import org.openbpm.base.rest.util.RequestUtil;
import org.openbpm.org.core.constant.RelationTypeConstant;
import org.openbpm.org.core.manager.GroupManager;
import org.openbpm.org.core.manager.OrgRelationManager;
import org.openbpm.org.core.model.OrgRelation;
import org.openbpm.org.rest.controller.OrgRelationController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/etech/orgRelation")
public class EtechRelationController extends OrgRelationController {

    @Resource
    EtechRelationService etechRelationService;
    @Resource
    EtechGroupService etechGroupService;
    @Resource
    OrgRelationManager orgRelationManager;
    @Resource
    OrgRelationMapper orgRelationMapper;
    @Resource
    GroupManager groupManager;
    @Autowired
    EtechUserController userController;

    /**
     * 从部门班组配置中同步主管内勤助理角色人员
     *
     * @return
     */
    @RequestMapping("syncRole")
    @CatchErr("同步主管内勤助理角色失败")
    public ResultMsg syncRole(@RequestParam("rolename") String roleNames) {
        etechRelationService.syncRole(roleNames);
        return getSuccessResult();
    }


    @RequestMapping({"queryGroupUser"})
    @CatchErr
    public PageResult queryGroupUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String groupId = RequestUtil.getRQString(request, "groupId", "查询 组用户 组ID 不能为空");
        QueryFilter filter = this.getQueryFilter(request);
        filter.addFilter("tgroup.id_", groupId, QueryOP.EQUAL);
        filter.addFilter("relation.type_", Arrays.asList(RelationTypeConstant.GROUP_USER.getKey(), RelationTypeConstant.POST_USER.getKey()), QueryOP.IN);
        Page pageList = (Page) this.orgRelationManager.query(filter);

        String groupFullName = etechGroupService.getFullGroupName(groupId);

        List res = (List) pageList.parallelStream()
                .map(a -> {
                    Map<String, Object> map = BeanUtil.beanToMap(a);
                    map.put("groupFullName", groupFullName);
                    try {
                        EtechUser user = userController.getUser(map.get("userId").toString());
                        map.put("email", user.getEmail());
                        map.put("phone", user.getMobile());
                        map.put("lastLogin", user.getLastLogin());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    // map.put("groupOrgRelations",etechGroupService.getOrgRelationByGroup(groupId));
                    return map;
                }).collect(Collectors.toList());

        pageList.clear();
        pageList.addAll(res);
        return new PageResult(pageList);
    }

    @RequestMapping({"queryGroupUser2"})
    @CatchErr
    public PageResult queryGroupUser2(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String groupId = RequestUtil.getRQString(request, "groupId", "查询 组用户 组ID 不能为空");
        List<String> groupIds = etechGroupService.getAllDprtIdsByDprtId(groupId);
        QueryFilter filter = this.getQueryFilter(request);
        filter.addFilter("tgroup.id_", groupIds, QueryOP.IN);
        filter.addFilter("relation.type_", Arrays.asList(RelationTypeConstant.GROUP_USER.getKey(), RelationTypeConstant.POST_USER.getKey()), QueryOP.IN);
        Page pageList = (Page) this.orgRelationManager.query(filter);
        List res = (List) pageList.parallelStream()
                .map((a) -> {
                    Map<String, Object> map = BeanUtil.beanToMap(a);
                    String groupFullName = etechGroupService.getFullGroupName(map.get("groupId").toString());
                    map.put("groupFullName", groupFullName);
                    try {
                        EtechUser user = userController.getUser(map.get("userId").toString());
                        map.put("email", user.getEmail());
                        map.put("phone", user.getMobile());
                        map.put("lastLogin", user.getLastLogin());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    // map.put("groupOrgRelations",etechGroupService.getOrgRelationByGroup(groupId));
                    return map;
                }).collect(Collectors.toList());

        pageList.clear();
        pageList.addAll(res);

        return new PageResult(pageList);
    }

    @RequestMapping("saveAllOrg")
    @CatchErr("保存人员组织失败")
    @Transactional(rollbackFor = Exception.class)
    public ResultMsg saveAllOrg(@RequestParam("groupId") String groupId, @RequestBody List<Map<String, Object>> users) {
        // TODO
        String[] usersId = new String[users.size()];
        for (int i = 0; i < users.size(); i++) {
            //System.out.println(users.get(i));
            usersId[i] = users.get(i).get("userId").toString();
        }
        //System.out.println(Arrays.asList(usersId));
        // 删除原有所有的用户组织关系
        etechRelationService.removeUserGroup(Arrays.asList(usersId));
        // 保存新的用户组织关系
        this.orgRelationManager.saveUserGroupRelation(groupId, null, usersId);
        setupUserMaster(usersId);

        return getSuccessResult();
    }

    @RequestMapping("delete")
    @CatchErr("作废组织失败")
    @Transactional(rollbackFor = Exception.class)
    public ResultMsg deleteOrg(@RequestParam("groupId") String groupId) {
        etechRelationService.deleteGroup(groupId);
        return getSuccessResult();
    }


    @RequestMapping("refreshGroupView")
    @CatchErr("同步组织实体失败")
    public ResultMsg refreshGroupView() {
        etechGroupService.refreshGroupView();
        return getSuccessResult();
    }

    // TODO
    @RequestMapping("saveGroupUserRel")
    @CatchErr("同步组织实体失败")
    public ResultMsg saveGroupUserRel(HttpServletRequest request, HttpServletResponse response) {
        String groupId = RequestUtil.getRQString(request, "groupId");
        String[] userIds = RequestUtil.getStringAryByStr(request, "userIds");
        if (ArrayUtil.isEmpty(userIds)) {
            throw new BusinessError("请选择用户");
        } else {
            // 删除原有所有的用户组织关系
            etechRelationService.removeUserGroup(Arrays.asList(userIds));
            // 保存新的用户组织关系
            this.orgRelationManager.saveUserGroupRelation(groupId, null, userIds);

            setupUserMaster(userIds);
            return this.getSuccessResult("添加成功");
        }
    }

    public void setupUserMaster(String[] userIds) {
        for (String id : userIds) {
            List<OrgRelation> relations = this.orgRelationManager.getUserRelation(id, RelationTypeConstant.GROUP_USER.getKey());
            for (OrgRelation relation : relations) {
                this.orgRelationManager.updateUserGroupRelationIsMaster(relation.getId());
            }
        }
    }

    @RequestMapping({"roleJson"})
    public PageResult roleJson(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String roleId = RequestUtil.getRQString(request, "roleId", "查询 角色ID不能为空");
        QueryFilter filter = this.getQueryFilter(request);
        filter.addFilter("role.id_", roleId, QueryOP.EQUAL);
        filter.addFilter("relation.type_", RelationTypeConstant.USER_ROLE.getKey(), QueryOP.EQUAL);
        Page<com.sec.etech.org.model.OrgRelation> pageList = (Page) this.orgRelationMapper.queryFilter(filter);
        return new PageResult(pageList);
    }

    @RequestMapping({"getRemark"})
    @CatchErr
    public ResultMsg getRemark(@RequestParam String id) throws Exception {
        com.sec.etech.org.model.OrgRelation orgRelation = this.etechRelationService.getDataById(id);
        if (orgRelation != null) {
            return this.getSuccessResult(orgRelation);
        }
        return getWarnResult("数据不存在或者已删除！");
    }

    @RequestMapping({"editRemark"})
    @CatchErr
    public ResultMsg editRemark(@RequestBody com.sec.etech.org.model.OrgRelation orgRelation) throws Exception {
        etechRelationService.editRemark(orgRelation);
        return getSuccessResult();
    }

    @RequestMapping({"exportList"})
    @CatchErr
    public void exportList(@RequestParam String roleId, @RequestParam(required = false) String fullname,
                           HttpServletResponse response) throws Exception {
        etechRelationService.exportList(roleId, fullname, response);
    }
}
